package org.itboys.mobile.service.mysql.web.order;

import com.alipay.api.response.AlipayTradeRefundResponse;
import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.framework.excel.ExcelUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.order.SundayOrderProductMapper;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.order.SundayOrder;
import org.itboys.mobile.entity.mysql.order.SundayOrderProduct;
import org.itboys.mobile.entity.mysql.pay.SundayPayConfig;
import org.itboys.mobile.entity.mysql.wallet.SundayWallet;
import org.itboys.mobile.service.mongo.front.SundayFrontMemberService;
import org.itboys.mobile.service.mysql.front.SundayFrontWalletService;
import org.itboys.mobile.service.mysql.web.pay.SundayPayConfigService;
import org.itboys.mobile.util.DatetUtil;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.itboys.pay.alipay.AlipayMobileService;
import org.itboys.pay.weixin.WeixinPayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.security.provider.Sun;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 作者：jiangxiong
 * 日期：2016年11月25日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_订单_后台_service
 */
@Service
public class SundayOrderService extends BaseMySqlService<SundayOrder> {
	@Autowired
	private SundayOrderProductMapper orderProductMapper;

	@Autowired
	private SundayFrontWalletService walletService;
	@Autowired
	private SundayPayConfigService payConfigService;


	@Autowired
	private SystemDictionaryService dictionaryService;
	@Autowired
	private SundayFrontMemberService memberService;
	@Autowired
	private ResourceHolder resourceHolder;
	/**
	 * 分页获取订单
	 * @param request
	 * @param orderStatus
	 * * @param discountWay 1使用优惠券2使用爱购币3使用余额4使用贝壳
	 * @return
	 */
	public PageResult<SundayOrder> selectOrder(HttpServletRequest request, Integer orderStatus,Integer discountWay) throws  Exception{
		Map<String,Object> param = ParamUtil.packageMysqlPageParam(request,"orderNo","receiveName","memberName","title","shopId");
		if(orderStatus!=null){
			param.put("status",orderStatus);
		}
		//处理时间查询
		String ct_start =request.getParameter("ct_start");
		if(StringUtils.isNotEmpty(ct_start)){
			ct_start= TimeUtils.formatToTime(DatetUtil.setDateStart(new SimpleDateFormat("yyyy-MM-dd").parse(ct_start)));
			param.put("ct_start",ct_start);
		}
		String ct_end= request.getParameter("ct_end");
		if(StringUtils.isNotEmpty(ct_end)){
			ct_end= TimeUtils.formatToTime(DatetUtil.setDateEnd(new SimpleDateFormat("yyyy-MM-dd").parse(ct_end)));
			param.put("ct_end",ct_end);
		}
		//处理抵扣方式
		//1使用优惠券2使用爱购币3使用余额4使用贝壳
		if(discountWay!=null){
			if(discountWay==1){
				param.put("usedCoupon",1);
			}else if(discountWay==2){
				param.put("usedAigou",1);
			}else if(discountWay==3){
				param.put("usedBalance",1);
			}else if(discountWay==4){
				param.put("usedConch",1);
			}
		}

		return  new PageResult<SundayOrder>(super.select(param),super.count(param));
	}

	/**
	 * 查询订单详情
	 * @param orderId
	 * @return
	 */
	public SundayOrder findOne(Long orderId){
		SundayOrder order = super.find(orderId);
		return order;
	}
	//分页获取订单商品
	public PageResult<SundayOrderProduct> selectOrderProduct(HttpServletRequest request,long orderId){
		Map<String,Object> param = ParamUtil.packageMysqlPageParam(request,"");
		param.put("orderId",orderId);
		long count = Long.valueOf(orderProductMapper.count(param).toString());
		return  new PageResult<SundayOrderProduct>(orderProductMapper.select(param),count);
	}


	/**
	 * 配送订单
	 * @param orderId
	 * @param sendCompany
	 * @param sendCompanyCode
	 * @param sendCode
	 */
	public void sendOrder(Long orderId, String sendCompany, String sendCompanyCode,  String sendCode){
		SundayOrder order = super.find(orderId);
		if(order.getStatus()!= SundayCommonConstants.ORDER_STATUS_DFH){
			throw new ErrorException("系统错误，请刷新后重试");
		}
		order.setSendCompany(sendCompany);
		order.setSendCompanyCode(sendCompanyCode);
		order.setSendCode(sendCode);
		order.setStatus(SundayCommonConstants.ORDER_STATUS_PSZ);
		super.update(order);
	}

	/**
	 * 订单退款,退货
	 * @param orderId	订单id
	 * @param type	类型:1-退款,2-退货
	 */
	@Transactional
	public void back(Long orderId,Integer type) throws Exception{
		SundayOrder order = super.find(orderId);
		if(order.getStatus()!= SundayCommonConstants.ORDER_STATUS_DTK&&
				order.getStatus()!= SundayCommonConstants.ORDER_STATUS_DTH&&
				order.getType()== SundayCommonConstants.type_aigou){
			throw new ErrorException("系统错误，请刷新后重试");
		}
		//1，判断在线支付金额
		if(order.getPayAmount().compareTo(new BigDecimal("0"))==1){
			SundayPayConfig payConfig = payConfigService.getPayConfig(order.getPayType());;
			//2，判断支付方式
			//2.1,微信公众号支付，2.2，微信开放平台支付
			if(order.getPayType()==SundayCommonConstants.pay_type_wechatpay_html||
					order.getPayType()==SundayCommonConstants.pay_type_wechatpay_open){
				String cer_path = null;
				//微信退款证书路径
				if(order.getPayType()==SundayCommonConstants.pay_type_wechatpay_html){
					cer_path="/aigou/project/aigou/pay/weixin/html/apiclient_cert.p12";
				}
				if(order.getPayType()==SundayCommonConstants.pay_type_wechatpay_open){
					cer_path="/aigou/project/aigou/pay/weixin/open/apiclient_cert.p12";
				}
				logger.info("---------------证书路径--------"+cer_path);
				String outRefundNo= NumberUtil.generateNumber("WXRE");
				Integer totalFee=Integer.valueOf(order.getPayAmount().multiply(new BigDecimal("100")).setScale(0,BigDecimal.ROUND_HALF_UP).toString());
				Integer refundFee=Integer.valueOf(order.getPayAmount().multiply(new BigDecimal("100")).setScale(0,BigDecimal.ROUND_HALF_UP).toString());
				Map<String,String> result = WeixinPayUtils.Refund(payConfig.getWeChatAppId(), payConfig.getWeChatMchId(), order.getPayNo(), outRefundNo,  totalFee,  refundFee,payConfig.getWeChatApi(),cer_path);
				String result_code=result.get("result_code");
				if(result_code.equalsIgnoreCase("SUCCESS")){
						order.setRefundNo(result.get("out_refund_no"));
						order.setRefundAmount(new BigDecimal(result.get("refund_fee")));
				}else{
					throw new ErrorException("微信在线退款失败，请联系管理员");
				}
				//2.3，支付宝支付
			}else if(order.getPayType()== SundayCommonConstants.pay_type_alipay){

				String result=AlipayMobileService.refund(order.getPayNo(), null, order.getPayAmount().setScale(2,BigDecimal.ROUND_HALF_UP).toString(),
						payConfig.getAlipayAppId(),payConfig.getAlipayAppPrivateKey(), payConfig.getAlipayPublicKey());
				if(!result.equalsIgnoreCase(CommonConstants.SUCCESS)){
					throw new ErrorException("支付宝在线退款失败，请联系管理员");
				}
			}

		}




		if(type ==1){//退款
			if(order.getStatus() != SundayCommonConstants.ORDER_STATUS_DTK){
				throw new ErrorException("订单状态有误,请联系管理员!");
			}
			//变更状态
			order.setStatus(SundayCommonConstants.ORDER_STATUS_YTK);
		}else{//退货
			if(order.getStatus() != SundayCommonConstants.ORDER_STATUS_DTH){
				throw new ErrorException("订单状态有误,请联系管理员!");
			}
			//变更状态
			order.setStatus(SundayCommonConstants.ORDER_STATUS_YTH);
		}


		//需退还的余额-退至钱包余额
		BigDecimal needBackBalance = new BigDecimal(0);
		//需退还爱购币。2018年3月17日，不退还爱购币
		//BigDecimal needBackAigou = new BigDecimal(0);
		//需退还的贝壳-退至钱包贝壳
		BigDecimal needBackConch = new BigDecimal(0);
		if(order.getConchUsedAmount() != null){
			needBackConch = order.getConchUsedAmount();
		}
		if(order.getBalanceUsedAmount() != null){
			needBackBalance = order.getBalanceUsedAmount();
		}
		SundayWallet wallet = walletService.getByMemberId(order.getMemberId());
		//返还支付的金额和爱购币
		wallet.setAigouCoin(wallet.getConch().add(needBackConch));
		wallet.setTotalAmount(wallet.getTotalAmount().add(needBackBalance));
		walletService.update(wallet);
		super.update(order);
	}

	/**
	 * 取消订单
	 * @param orderId
	 */
	public void cancelOrder(Long orderId){
		SundayOrder order=checkOrder(orderId,SundayCommonConstants.ORDER_STATUS_DFK);
		order.setStatus(SundayCommonConstants.ORDER_STATUS_YQX);
		//需退还的余额-退至钱包余额
		BigDecimal needBackBalance = new BigDecimal(0);
		//需退还爱购币
		BigDecimal needBackAigou = new BigDecimal(0);

		if(order.getAiGouUsedCoin() != null){
			needBackAigou = order.getAiGouUsedCoin();
		}
		if(order.getBalanceUsedAmount() != null){
			needBackBalance = order.getBalanceUsedAmount();
		}
		SundayWallet wallet = walletService.getByMemberId(order.getMemberId());
		//返还支付的金额和爱购币
		wallet.setAigouCoin(wallet.getAigouCoin().add(needBackAigou));
		wallet.setTotalAmount(wallet.getTotalAmount().add(needBackBalance));
		walletService.update(wallet);

		super.update(order);
	}


	/**
	 * 将订单商品生成excel
	 * @param orderId
	 */
	public void excel(Long orderId,String orderNo){
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("orderId",orderId);
		List<SundayOrderProduct> products=orderProductMapper.select(param);

		//生成excel记录
		//excel中对应的标题
		List<String> titlesArray = new ArrayList<String>();
		titlesArray.add("商品名称");
		titlesArray.add("编号");
		titlesArray.add("规格");
		titlesArray.add("数量");
		titlesArray.add("销售价格");
		//商品属性中标题对应的字段
		List<String> fieldsArray = new ArrayList<String>();
		fieldsArray.add("name");
		fieldsArray.add("barCode");
		fieldsArray.add("standard");
		fieldsArray.add("num");
		fieldsArray.add("price");
		String [] fields = (String [])fieldsArray.toArray((new String[fieldsArray.size()]));
		String [] titles = (String [])titlesArray.toArray((new String[titlesArray.size()]));
		//配置文件输出流
		//System.out.println("文件位置"+outFile.;);
		//设置文件位置
		String fileName = orderNo+".xls";
		//String savePath=fileName;
		//	String savePath="D:/_projects/sunday/tianjiefinance/static/upload/"+fileName;
		String file_path=resourceHolder.getStringValue("fileUploadPath")+"/excel/"+fileName;
		//String resultPath=File.separator+"excel"+File.separator+fileName;
		try {
			OutputStream out = new FileOutputStream(new File(file_path),false);
			ExcelUtils.exportExcelFile2("sheet1", null, titles, fields, products, out,0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		SundayOrder order = new SundayOrder();
		order.setId(orderId);
		order.setExcelUrl("/excel/"+fileName);
		super.update(order);

		//logger.info("------------下载路径："+file_path);
		//return"/excel/"+fileName;
	}
	/**
	 * 校验订单状态
	 * @param orderId
	 * @param status
	 */
	public SundayOrder checkOrder(Long orderId,Integer status){
		SundayOrder order = super.find(orderId);
		if(order.getStatus()!=status){
			throw new ErrorException(CommonConstants.ERROMSG);
		}
		return order;
	}

}
